﻿using UnityEngine;
using System.Collections.Generic;
using Dict.DataModel;
using ProtoBuf.Message;

namespace UI
{
    public class UIUnionFightMapPage : MonoBehaviour
    {
        public static bool notShowAgain = false;
        //public static bool isReceiveOrder;
        public UISprite playerPic;
        public UISprite npcPic;
        public UISprite minePic;
        public UILabel gatherCd;
        public UIUnionFightGatherPoint gatherSetPage;
        public GameObject tips;
        public Transform roleParent;

        List<UISprite> mineList = new List<UISprite>();
        List<UISprite> allIcon = new List<UISprite>();
        float scaleBig = 5.2f;
        long endTime;
        float currTime;
        Vector3 clickPos;
        public void Init()
        {
            gameObject.SetActive(true);
            GetComponent<PageTweener>().Play();
            MiniMapComponent.Instance.SetUnionFightOrderShow(false);

            LoadDataFromTable();
            LoadMineDataFromSever();
            NetAPI.RegistSocketHandler(OpDefine.SCUFResourcePointSpawn, SCUFResourseUpdate);//资源出生刷新
            NetAPI.RegistSocketHandler(OpDefine.SCUFPlayerCollectEnd, SCUFResourseUpdate);//玩家结束采集

        }

        public void Close()
        {
            NetAPI.UnregisterSocketHandler(OpDefine.SCUFResourcePointSpawn, SCUFResourseUpdate);//资源出生刷新
            NetAPI.UnregisterSocketHandler(OpDefine.SCUFPlayerCollectEnd, SCUFResourseUpdate);//玩家结束采集
            clean();
            gameObject.SetActive(false);
        }

        void SCUFResourseUpdate(object obj)
        {
            DestroyMine();
            Invoke("LoadMineDataFromSever",0.1f);
        }

        bool isHaveCd;
        public bool GatherCd
        {
            set
            {
                isHaveCd = value;
                gatherCd.gameObject.SetActive(isHaveCd);
                gatherCd.text = string.Format(TableTextBlo.GetText("union_fight_set_point_cdTime"), (int)currTime);
            }
            get
            {
                return isHaveCd;
            }
        }

        void Update()
        {
            currTime = (endTime - ServerTimerTool.CurrentUTCJavaTime()) / 1000f;
            GatherCd = (currTime > 0 && endTime > 0);
        }

        void LoadDataFromTable()
        {
            var listNpcs = Dict.Blo.DictUnionFightNpcBlo.GetAll();
            var towerList = Dict.Blo.DictUnionFightTowerBlo.GetAll();
            var factoryList = Dict.Blo.DictUnionFightFactoryBlo.GetAll();
            foreach (var aa in listNpcs)
            {
                var pos = aa.Position.Split(',');
                SetIconPos(pos);
            }
            foreach (var tower in towerList)
            {
                var pos = tower.Position.Split(',');
                SetIconPos(pos);
            }
            foreach (var fac in factoryList)
            {
                var pos = fac.Position.Split(',');
                SetIconPos(pos);
            }
            setPlayerInMap();
        }

        void LoadMineDataFromSever()
        {
            var mineRes = UIUnionFightRunMap.GetNetData().netResource;
            var mines = mineRes.resources;

            foreach(var mine in mines)
            {
                var pos = mineRes.GetPosition(mine.Value.guid);
                setMineInMap(pos);
            }
        }

        //矿消失
        void DestroyMine()
        {
            foreach(var mine in mineList)
            {
                if (mine != null)
                    Destroy(mine);
            }
            mineList.Clear();
        }

        void DestroyAll()
        {
            foreach (var icon in allIcon)
            {
                if (icon != null)
                    Destroy(icon.gameObject);
            }
            allIcon.Clear();
        }

        void SetIconPos(string[] pos)
        {
            if (pos.Length == 3)
            {
                float pos_x = float.Parse(pos[0]);
                float pos_y = float.Parse(pos[1]);
                float pos_z = float.Parse(pos[2]);
                var worldPos = new Vector3(pos_x, pos_y, pos_z);
                setIconInMap(worldPos);
            }
        }

        void setPlayerInMap()
        {
            var playerCopy = Instantiate(playerPic);
            playerCopy.transform.parent = roleParent;
            playerCopy.MakePixelPerfect();
            playerCopy.transform.localScale = Vector3.one;
            playerCopy.gameObject.SetActive(true);
            allIcon.Add(playerCopy);
            var self = Room.RoomManager.currentRoom.charactorManager.GetSelfCharactor();
            var z = self.transform.localRotation.eulerAngles.y;
            playerCopy.transform.localRotation = Quaternion.Euler(new Vector3(0, 180, z + 75));
            playerCopy.transform.localPosition = GetTransPositionBig(self.transform.localPosition);
        }

        void setIconInMap(Vector3 npcPos)
        {
            var npcCopy = Instantiate(npcPic);
            npcCopy.transform.parent = roleParent;
            //emptyNpc.spriteName = "";
            npcCopy.transform.localScale = Vector3.one;
            npcCopy.MakePixelPerfect();
            npcCopy.gameObject.SetActive(true);
            npcCopy.transform.localPosition = GetTransPositionBig(npcPos);
            allIcon.Add(npcCopy);
        }

        void setMineInMap(Vector3 npcPos)
        {
            var mineCopy = Instantiate(minePic);
            mineCopy.transform.parent = roleParent;
            mineCopy.name = "mine";
            mineList.Add(mineCopy);
            //emptyNpc.spriteName = "";
            mineCopy.transform.localScale = Vector3.one;
            mineCopy.MakePixelPerfect();
            mineCopy.gameObject.SetActive(true);
            allIcon.Add(mineCopy);
            mineCopy.transform.localPosition = GetTransPositionBig(npcPos);
        }

        public Vector3 GetTransPositionBig(Vector3 worldPosition)
        {
            Vector3 p = worldPosition;
            p.x = worldPosition.x * scaleBig;
            p.y = worldPosition.z * scaleBig;
            p.z = 0;
            return p;
        }

        Vector3 GetWorldPosition(Vector3 pos)
        {
            Vector3 p = pos;
            p.x = pos.x / scaleBig;
            p.y = 0;
            p.z = pos.y / scaleBig;
            return p;
        }

        //会长设置集结点
        public void SetGatherPoint()
        {
            if (!CheckiIdentity())
                return;
            clickPos = UICamera.mainCamera.ScreenToWorldPoint(Input.mousePosition);
            if (notShowAgain)
            {
                SetPoint();
            }
            else
            {
                gatherSetPage.Init(SetPoint);
            }
        }

        bool CheckiIdentity()
        {
            if(endTime > 0)
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("operation_cd_ing"));
                return false;
            }
            //测试    记得改回来
            int identity = UIUnionFightRunMap.GetNetData().netActor.players[StaticData.playerData.playerId].unionAuthority;
            if (identity != 2)
                return true;
            
            //点击特效
            var pos = UICamera.mainCamera.ScreenToWorldPoint(Input.mousePosition);
            Tool.ScreenEffectTool.Instance.OnClick0(pos);

            return true;
        }

        public void SetEnemyGatherPoint(GameObject camp)
        {
            if (!CheckiIdentity())
                return;

            if (!CheckIsCanGather(camp))
            {
                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("union_fight_cannot_setPoint_tips"));
                return;
            }
            else
            {
                clickPos = UICamera.mainCamera.ScreenToWorldPoint(Input.mousePosition);
                if (notShowAgain)
                {
                    SetPoint();
                }
                else
                {
                    gatherSetPage.Init(SetPoint);
                }
            }
        }

        private Vector3 SamplePosition(Vector3 target,out bool canGo)
        {
            NavMeshHit hit;
            Vector3 pos=Vector3.zero;
            canGo = NavMesh.SamplePosition(target, out hit, 100f, NavMesh.AllAreas);
            if (canGo)
            {
                pos = hit.position;
            }

            return pos;
        }

        //点击前往集结点
        public void ClickGatherPoint()
        {
            MiniMapComponent.Instance.SetUnionFightOrderShow(false);
            var self = Room.RoomManager.currentRoom.charactorManager.GetSelfCharactor();
            if(self != null)
            {
                var ai = self.ai as Room.RCAIUnionSelf;
                if (ai != null && ai.IdleState())
                {
                    //Debug.Log("---------------------点击前往的位置: " + GetWorldPosition(tips.transform.localPosition));
                    //GameObject obj = GameObject.CreatePrimitive(PrimitiveType.Sphere);
                    //obj.transform.position = GetWorldPosition(tips.transform.localPosition);
                    //obj.name = "球";
                    bool canGo;
                    Vector3 tagerPos = SamplePosition(GetWorldPosition(tips.transform.localPosition), out canGo);
                    if(canGo)
                    {
                        ai.AutoGoto(tagerPos, () =>
                        {
                            //todo:
                            if (ai.IdleState())
                            {
                                BoxManager.CreatePopupTextBox(TableTextBlo.GetText("union_fight_arrive_point"));
                            }
                        });
                    }
                    else
                    {
                        BoxManager.CreatePopupTextBox("该地点不能到达");
                    }
                }
            }
            ShowTips(false);
            Close();
        }

        //发送消息给服务器  设置集结点
        void SetPoint()
        {
            UIUnionFightRunMap.GetNetData().SendCSUFLeaderFocus(clickPos);
        }

        //收到集结点消息的回调
        public void ShowGatherTips(PointNew pos,long cdTime = 0)
        {
            clickPos.x = pos.x;
            clickPos.y = pos.y;
            clickPos.z = pos.z;
            tips.transform.position = clickPos;
            tips.transform.localPosition -= Vector3.up * 28;  //这是个诡异的偏移量
            this.endTime = cdTime;
            ShowTips(true);
            MiniMapComponent.Instance.SetUnionFightOrderShow(true);
            MiniMapComponent.Instance.SetGatherPoint(true, GetWorldPosition(tips.transform.localPosition));
        }

        public void HideGatherTips()
        {
            ShowTips(false);
            MiniMapComponent.Instance.SetUnionFightOrderShow(false);
            MiniMapComponent.Instance.SetGatherPoint(false);
            endTime = 0;
        }

        void ShowTips(bool value)
        {
            if(tips != null)
            {
                tips.SetActive(value);
            }
        }

        //如果集结点在敌区，检测对方城门是否攻破
        bool CheckIsCanGather(GameObject camp)
        {
            bool isCanGather = false;
            var gates = UIUnionFightRunMap.GetNetData().netGate.gates;
            int selfCamp = UIUnionFightRunMap.GetNetData().charactorManager.GetSelfCharactor().Camp;
            if ((selfCamp == 0 && camp.name == "left") || (selfCamp == 1 && camp.name == "right"))
                return true;
            foreach (var gate in gates)
            {
                int state = UIUnionFightRunMap.GetNetData().netGate.GetState(gate.Value.guid);
                if (gate.Value.camp != selfCamp && (UnionGateState)state == UnionGateState.Destroy)
                {
                    isCanGather = true;
                }
            }
            return isCanGather;
        }

        void clean()
        {
            DestroyAll();
        }

    }
}

